﻿using SQLiteSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using YunLuPos.Entity;

namespace YunLuPos.DB.Service
{
    public class CodesService
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CodesService));
        /**
        * 根据条码或商品编码获取商品
        * */
        public String genNowOrderCode(String shopCode,String posCode)
        {
            DBLocker.setLocker();
            try
            {
                String dataStr = DateTime.Now.ToString("yyyyMMdd");
                System.Random random = new System.Random();
                int i = random.Next(100000, 999999);
                String seq = String.Format("{0:D6}", i);
                String code = posCode + dataStr +seq;
                Trace.WriteLine(code);
                using (SqlSugarClient db = SugarDao.GetInstance())
                {
                    Codes dbCode = db.Queryable<Codes>()
                            .Where(it => it.orderCode == code)
                            .SingleOrDefault();
                    Trace.WriteLine(dbCode);
                    if (dbCode == null)
                    {
                        Codes newCode = new Codes();
                        newCode.orderCode = code;
                        Int64 result = (Int64)db.Insert(newCode);
                        Trace.WriteLine(result);
                        if (result > 0)
                        {
                            return code;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            finally
            {
                DBLocker.release();
            }
            return null;
        }

        public String genPayOutTradeNo(String orderCode)
        {
            if (orderCode == null)
            {
                return "";
            }
            System.Random random = new System.Random();
            int i = random.Next(10, 99);
            String seq = String.Format("{0:D2}", i);
            return seq + orderCode;
        }

    }
}
